package wordcount;


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.util.Random;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;


import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.map.InverseMapper;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
public class wordcount {
    public static class TokenizerMapper

            extends Mapper<Object, Text, Text, IntWritable>{
        static enum CountersEnum { INPUT_WORDS }
        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();
        private boolean caseSensitive;
        private Set<String> patternsToSkip = new HashSet<String>();
        private Configuration conf;
        private BufferedReader fis;
        private Set<String> wordstoskip = new HashSet<String>();

        public void setup(Context context) throws IOException,
                InterruptedException {
            conf = context.getConfiguration();
            caseSensitive = conf.getBoolean("wordcount.case.sensitive", true);
            if (conf.getBoolean("wordcount.skip.patterns", true)) {
                URI[] patternsURIs = Job.getInstance(conf).getCacheFiles();
                for (URI patternsURI : patternsURIs) {
                    if (patternsURI==patternsURIs[0]){
                        Path patternsPath = new Path(patternsURI.getPath());
                        String patternsFileName = patternsPath.getName().toString();
                        parseSkipFile(patternsFileName);
                    }
                }
            }
            if (conf.getBoolean("wordcount.skip.words", true)){
                URI[] patternsURIs = Job.getInstance(conf).getCacheFiles();
                for (URI patternsURI : patternsURIs) {
                    if (patternsURI!=patternsURIs[0]){
                        Path patternsPath = new Path(patternsURI.getPath());
                        String patternsFileName = patternsPath.getName().toString();
                        wordSkipFile(patternsFileName);
                    }
                }
            }
        }
        private void wordSkipFile(String filename){
            try {
                fis = new BufferedReader(new FileReader(filename));
                String pattern = null;
                while ((pattern = fis.readLine()) != null) {
                    wordstoskip.add(pattern);
                }
            } catch (IOException ioe) {
                System.err.println("Caught exception while parsing the cached file '"
                        + StringUtils.stringifyException(ioe));
            }
        }
        private void parseSkipFile(String fileName) {
            try {
                fis = new BufferedReader(new FileReader(fileName));
                String pattern = null;
                while ((pattern = fis.readLine()) != null) {
                    patternsToSkip.add(pattern);
                }
            } catch (IOException ioe) {
                System.err.println("Caught exception while parsing the cached file '"
                        + StringUtils.stringifyException(ioe));
            }
        }
        private static boolean isNumber(String str){

            String reg = "^[0-9]+(.[0-9]+)?$";

            return str.matches(reg);

        }

        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            String line = (caseSensitive) ?
                    value.toString() : value.toString().toLowerCase();
            for (String pattern : patternsToSkip) {
                line = line.replaceAll(pattern, "");
            }
            StringTokenizer itr = new StringTokenizer(line);
            while (itr.hasMoreTokens()) {
                word.set(itr.nextToken());
                if (word.getLength()>=3 && !wordstoskip.contains(word.toString()) && !isNumber(word.toString())){
                    String path = ((FileSplit)context.getInputSplit()).getPath().toString();
                    int index = path.lastIndexOf("/");
                    String fileName = path.substring(index+1);
                    String tmp = word.toString();
                    String temp = tmp+'@'+fileName;
                    word.set(temp);
                    context.write(word, one);
                    Counter counter = context.getCounter(CountersEnum.class.getName(),
                            CountersEnum.INPUT_WORDS.toString());
                    counter.increment(1);
                }
            }
        }
    }
    
    //整体
    public static class TokenizerMapper1

            extends Mapper<Object, Text, Text, IntWritable>{
        static enum CountersEnum { INPUT_WORDS }
        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();
        private boolean caseSensitive;
        private Set<String> patternsToSkip = new HashSet<String>();
        private Configuration conf;
        private BufferedReader fis;
        private Set<String> wordstoskip = new HashSet<String>();

        public void setup(Context context) throws IOException,
                InterruptedException {
            conf = context.getConfiguration();
            caseSensitive = conf.getBoolean("wordcount.case.sensitive", true);
            if (conf.getBoolean("wordcount.skip.patterns", true)) {
                URI[] patternsURIs = Job.getInstance(conf).getCacheFiles();
                for (URI patternsURI : patternsURIs) {
                    if (patternsURI==patternsURIs[0]){
                        Path patternsPath = new Path(patternsURI.getPath());
                        String patternsFileName = patternsPath.getName().toString();
                        parseSkipFile(patternsFileName);
                    }
                }
            }
            if (conf.getBoolean("wordcount.skip.words", true)){
                URI[] patternsURIs = Job.getInstance(conf).getCacheFiles();
                for (URI patternsURI : patternsURIs) {
                    if (patternsURI!=patternsURIs[0]){
                        Path patternsPath = new Path(patternsURI.getPath());
                        String patternsFileName = patternsPath.getName().toString();
                        wordSkipFile(patternsFileName);
                    }
                }
            }
        }
        private void wordSkipFile(String filename){
            try {
                fis = new BufferedReader(new FileReader(filename));
                String pattern = null;
                while ((pattern = fis.readLine()) != null) {
                    wordstoskip.add(pattern);
                }
            } catch (IOException ioe) {
                System.err.println("Caught exception while parsing the cached file '"
                        + StringUtils.stringifyException(ioe));
            }
        }
        private void parseSkipFile(String fileName) {
            try {
                fis = new BufferedReader(new FileReader(fileName));
                String pattern = null;
                while ((pattern = fis.readLine()) != null) {
                    patternsToSkip.add(pattern);
                }
            } catch (IOException ioe) {
                System.err.println("Caught exception while parsing the cached file '"
                        + StringUtils.stringifyException(ioe));
            }
        }
        private static boolean isNumber(String str){

            String reg = "^[0-9]+(.[0-9]+)?$";

            return str.matches(reg);

        }




        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            String line = (caseSensitive) ?
                    value.toString() : value.toString().toLowerCase();
            for (String pattern : patternsToSkip) {
                line = line.replaceAll(pattern, "");
            }
            StringTokenizer itr = new StringTokenizer(line);
            while (itr.hasMoreTokens()) {
                word.set(itr.nextToken());
                if (word.getLength()>=3 && !wordstoskip.contains(word.toString()) && !isNumber(word.toString())){
                    context.write(word, one);
                    Counter counter = context.getCounter(CountersEnum.class.getName(),
                            CountersEnum.INPUT_WORDS.toString());
                    counter.increment(1);
                }
            }
        }
    }
    
    
    
    public static class IntSumReducer

            extends Reducer<Text,IntWritable,Text,IntWritable> {

        private IntWritable result = new IntWritable();

        public void reduce(Text key, Iterable<IntWritable> values,Context context) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get();

            }
            result.set(sum);
            context.write(key, result);
        }
    }
    static class SimplePartitioner extends Partitioner<IntWritable, Text> {

        @Override
        public int getPartition(IntWritable key, Text value, int numPartitions) {
            String value_tmp = value.toString();
            String[] sArray=value_tmp.split("@");
            String v= sArray[1];
            if (v.equals("shakespeare-alls-11.txt")) {
                return 0;
            }else if (v.equals("shakespeare-antony-23.txt")) {
                return 1;
            }else if (v.equals("shakespeare-as-12.txt")) {
                return 2;
            }else if (v.equals("shakespeare-comedy-7.txt")) {
                return 3;
            }else if (v.equals("shakespeare-coriolanus-24.txt")) {
                return 4;
            }else if (v.equals("shakespeare-cymbeline-17.txt")) {
                return 5;
            }else if (v.equals("shakespeare-first-51.txt")) {
                return 6;
            }else if (v.equals("shakespeare-hamlet-25.txt")) {
                return 7;
            }else if (v.equals("shakespeare-julius-26.txt")) {
                return 8;
            }else if (v.equals("shakespeare-king-45.txt")) {
                return 9;
            }else if (v.equals("shakespeare-life-54.txt")) {
                return 10;
            }else if (v.equals("shakespeare-life-55.txt")) {
                return 11;
            }else if (v.equals("shakespeare-life-56.txt")) {
                return 12;
            }else if (v.equals("shakespeare-lovers-62.txt")) {
                return 13;
            }else if (v.equals("shakespeare-loves-8.txt")) {
                return 14;
            }else if (v.equals("shakespeare-macbeth-46.txt")) {
                return 15;
            }else if (v.equals("shakespeare-measure-13.txt")) {
                return 16;
            }else if (v.equals("shakespeare-merchant-5.txt")) {
                return 17;
            }else if (v.equals("shakespeare-merry-15.txt")) {
                return 18;
            }else if (v.equals("shakespeare-midsummer-16.txt")) {
                return 19;
            }else if (v.equals("shakespeare-much-3.txt")) {
                return 20;
            }else if (v.equals("shakespeare-othello-47.txt")) {
                return 21;
            }else if (v.equals("shakespeare-pericles-21.txt")) {
                return 22;
            }else if (v.equals("shakespeare-rape-61.txt")) {
                return 23;
            }else if (v.equals("shakespeare-romeo-48.txt")) {
                return 24;
            }else if (v.equals("shakespeare-second-52.txt")) {
                return 25;
            }else if (v.equals("shakespeare-sonnets-59.txt")) {
                return 26;
            }else if (v.equals("shakespeare-sonnets.txt")) {
                return 27;
            }else if (v.equals("shakespeare-taming-2.txt")) {
                return 28;
            }else if (v.equals("shakespeare-tempest-4.txt")) {
                return 29;
            }else if (v.equals("shakespeare-third-53.txt")) {
                return 30;
            }else if (v.equals("shakespeare-timon-49.txt")) {
                return 31;
            }else if (v.equals("shakespeare-titus-50.txt")) {
                return 32;
            }else if (v.equals("shakespeare-tragedy-57.txt")) {
                return 33;
            }else if (v.equals("shakespeare-tragedy-58.txt")) {
                return 34;
            }else if (v.equals("shakespeare-troilus-22.txt")) {
                return 35;
            }else if (v.equals("shakespeare-twelfth-20.txt")) {
                return 36;
            }else if (v.equals("shakespeare-two-18.txt")) {
                return 37;
            }else if (v.equals("shakespeare-venus-60.txt")) {
                return 38;
            }else if (v.equals("shakespeare-winters-19.txt")) {
                return 39;
            }
            return 0;
        }

    }

    public static class AutoReducer

            extends Reducer<IntWritable,Text,Text,NullWritable> {

        private int count = 0;
        private int flag = 0;
        public void reduce(IntWritable key, Iterable<Text> values,Context context) throws IOException, InterruptedException {
            
            for (Text v:values)
            {
                String v_string=v.toString();
                String[] sArray=v_string.split("@");
                String v_string_tmp = sArray[0];
                if(count==100){
                    if(flag ==0){
                    flag = 1;
                    String filename = sArray[1];
                    context.write(new Text(filename), NullWritable.get());
                    }
                    return;
                }
                count++;
                
                String res = count + ":"+ v_string_tmp + ", " + key.toString();
                context.write(new Text(res), NullWritable.get());

            }
        }
    }
    //

    public static class AutoReducer1

            extends Reducer<IntWritable,Text,Text,NullWritable> {

        private int count = 0;

        public void reduce(IntWritable key, Iterable<Text> values,Context context) throws IOException, InterruptedException {
            for (Text v:values)
            {
                if(count==100)
                    return;
                count++;
                String v_string=v.toString();
                String res = count + ":"+ v_string + ", " + key.toString();
                context.write(new Text(res), NullWritable.get());

            }
        }
    }
    private static class IntWritableDecreasingComparator extends IntWritable.Comparator {
        public int compare(WritableComparable a, WritableComparable b) {
            return -super.compare(a, b);
        }

        public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
            return -super.compare(b1, s1, l1, b2, s2, l2);
        }
    }
    public static void main(String[] args) throws Exception {

        Configuration conf = new Configuration();
        GenericOptionsParser optionParser = new GenericOptionsParser(conf, args);
        String[] remainingArgs = optionParser.getRemainingArgs();
        if (!(remainingArgs.length != 2 || remainingArgs.length != 4)) {
            System.err.println("Usage: wordcount <in> <out> [-skip skipPatternFile]");
            System.exit(2);
        }
        Path tempDir = new Path("wordcount-temp-" + Integer.toString(
                new Random().nextInt(Integer.MAX_VALUE)));
        Path tempDir1 = new Path("wordcount-temp1-" + Integer.toString(
                new Random().nextInt(Integer.MAX_VALUE)));
        Job job = Job.getInstance(conf, "word count");
        job.setJarByClass(wordcount.class);
        job.setMapperClass(TokenizerMapper.class);
        job.setCombinerClass(IntSumReducer.class);
        job.setReducerClass(IntSumReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        List<String> otherArgs = new ArrayList<String>();
        for (int i=0; i < remainingArgs.length; ++i) {
            if ("-skip".equals(remainingArgs[i])) {
                job.addCacheFile(new Path(remainingArgs[++i]).toUri());
                job.getConfiguration().setBoolean("wordcount.skip.patterns", true);  //新增属性“wordcount.skip.patterns”,设置为true
            }
            else if ("-ignore".equals(remainingArgs[i])){
                job.addCacheFile(new Path(remainingArgs[++i]).toUri());
                job.getConfiguration().setBoolean("wordcount.skip.words", true);  //新增属性“wordcount.skip.patterns”,设置为true
            }
            else{
                otherArgs.add(remainingArgs[i]);
            }
        }
        FileInputFormat.addInputPath(job, new Path(otherArgs.get(0)));
        FileOutputFormat.setOutputPath(job, tempDir);
        job.setOutputFormatClass(SequenceFileOutputFormat.class);
        if(job.waitForCompletion(true))
        {
            try{
                Job sortJob = new Job(conf, "sort");
                sortJob.setJarByClass(wordcount.class);

                FileInputFormat.addInputPath(sortJob, tempDir);
                sortJob.setInputFormatClass(SequenceFileInputFormat.class);
                /*InverseMapper由hadoop库提供，作用是实现map()之后的数据对的key和value交换*/
                sortJob.setMapperClass(InverseMapper.class);
                /*将 Reducer 的个数限定为40, 最终输出的结果文件就是40。*/
                sortJob.setNumReduceTasks(40);
                sortJob.setReducerClass(AutoReducer.class);
                sortJob.setPartitionerClass(SimplePartitioner.class);
                FileOutputFormat.setOutputPath(sortJob, new Path(otherArgs.get(1)));

                sortJob.setOutputKeyClass(IntWritable.class);
                sortJob.setOutputValueClass(Text.class);
                /*Hadoop 默认对 IntWritable 按升序排序，而我们需要的是按降序排列。
                 * 因此我们实现了一个 IntWritableDecreasingComparator 类,
                 * 并指定使用这个自定义的 Comparator 类对输出结果中的 key (词频)进行排序*/
                sortJob.setSortComparatorClass(IntWritableDecreasingComparator.class);
                if(sortJob.waitForCompletion(true)){
                    try{
                        Job job1 = Job.getInstance(conf, "word count1");
                        job1.setJarByClass(wordcount.class);
                        job1.setMapperClass(TokenizerMapper1.class);
                        job1.setCombinerClass(IntSumReducer.class);
                        job1.setReducerClass(IntSumReducer.class);
                        job1.setOutputKeyClass(Text.class);
                        job1.setOutputValueClass(IntWritable.class);
                        for (int i=0; i < remainingArgs.length; ++i) {
                            if ("-skip".equals(remainingArgs[i])) {
                                job1.addCacheFile(new Path(remainingArgs[++i]).toUri());
                                job1.getConfiguration().setBoolean("wordcount.skip.patterns", true);  //新增属性“wordcount.skip.patterns”,设置为true
                            }
                            else if ("-ignore".equals(remainingArgs[i])){
                                job1.addCacheFile(new Path(remainingArgs[++i]).toUri());
                                job1.getConfiguration().setBoolean("wordcount.skip.words", true);  //新增属性“wordcount.skip.patterns”,设置为true
                            }
                        }
                        FileInputFormat.addInputPath(job1, new Path(otherArgs.get(0)));
                        FileOutputFormat.setOutputPath(job1, tempDir1);
                        job1.setOutputFormatClass(SequenceFileOutputFormat.class);
                        if(job1.waitForCompletion(true))
                        {
                            try{
                                Job sortJob1 = new Job(conf, "sort1");
                                sortJob1.setJarByClass(wordcount.class);
                                FileInputFormat.addInputPath(sortJob1, tempDir1);
                                sortJob1.setInputFormatClass(SequenceFileInputFormat.class);
                                /*InverseMapper由hadoop库提供，作用是实现map()之后的数据对的key和value交换*/
                                sortJob1.setMapperClass(InverseMapper.class);
                                /*将 Reducer 的个数限定为1, 最终输出的结果文件就是一个。*/
                                sortJob1.setNumReduceTasks(1);
                                sortJob1.setReducerClass(AutoReducer1.class);
                                FileOutputFormat.setOutputPath(sortJob1, new Path(otherArgs.get(2)));
                                sortJob1.setOutputKeyClass(IntWritable.class);
                                sortJob1.setOutputValueClass(Text.class);
                                /*Hadoop 默认对 IntWritable 按升序排序，而我们需要的是按降序排列。
                                 * 因此我们实现了一个 IntWritableDecreasingComparator 类,
                                 * 并指定使用这个自定义的 Comparator 类对输出结果中的 key (词频)进行排序*/
                                sortJob1.setSortComparatorClass(IntWritableDecreasingComparator.class);
                                System.exit(sortJob1.waitForCompletion(true) ? 0 : 1);
                            }finally
                            {
                                FileSystem.get(conf).deleteOnExit(tempDir);
                            }
                            System.exit(0);

                        }
                        else
                        {
                            System.exit(1);
                        }
                    }finally {
                        FileSystem.get(conf).deleteOnExit(tempDir);
                    }
                    System.exit(0);
                }
                else
                {
                    System.exit(1);
                }
                //System.exit(sortJob.waitForCompletion(true) ? 0 : 1);
            }finally
            {
                FileSystem.get(conf).deleteOnExit(tempDir);
            }
            System.exit(0);

        }
        else
        {
            System.exit(1);
        }
    }
}